package com.step.ems.pages.wb

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.rememberNestedScrollInteropConnection
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.step.ems.R
import com.step.ems.api.WbArea
import com.step.ems.api.res.WbItem
import com.step.ems.component.MyTopBar
import com.step.ems.component.PageStatus
import com.step.ems.ui.theme.ContentBg
import com.step.ems.ui.theme.DarkBlue
import kotlinx.coroutines.launch

@Composable
fun WbItemScreen(
    viewModel: WbItemViewModel = hiltViewModel(),
) {
    val pages: List<List<WbItem>> by viewModel.dataGroup.collectAsStateWithLifecycle()
    val data by viewModel.data.collectAsStateWithLifecycle()
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()

    Scaffold(topBar = {
        MyTopBar(data.templateName.ifEmpty { stringResource(R.string.wbItem) })
    }) { padding ->
        PageStatus(
            uiState = uiState,
            total = pages.size,
            padding = padding,
            retry = { viewModel.getData() }) {
            WbItemScreenContent(padding, pages)
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun WbItemScreenContent(
    padding: PaddingValues,
    pages: List<List<WbItem>>,
) {
    if (pages.isEmpty()) {
        return
    }
    val pagerState = rememberPagerState(pageCount = { pages.size })
    val coroutineScope = rememberCoroutineScope()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(padding)
            .background(color = ContentBg)
    ) {
        Spacer(modifier = Modifier.height(1.dp))
        ScrollableTabRow(
            selectedTabIndex = pagerState.currentPage,
            edgePadding = 0.dp,
            divider = {},
            indicator = { tabPositions ->
                Row(
                    modifier = Modifier.tabIndicatorOffset(tabPositions[pagerState.currentPage]),
                    horizontalArrangement = Arrangement.Center,
                ) {
                    Box(
                        modifier = Modifier
                            .height(2.dp)
                            .width(20.dp)
                            .background(color = DarkBlue)
                    )
                }
            }
        ) {
            pages.forEachIndexed { index, page ->
                Tab(
                    selected = pagerState.currentPage == index,
                    onClick = { coroutineScope.launch { pagerState.animateScrollToPage(index) } },
                    text = { Text(text = stringResource(id = WbArea.getTitleRes(page[0].maintenanceArea))) },
                    unselectedContentColor = MaterialTheme.colorScheme.secondary
                )
            }
        }
        Spacer(modifier = Modifier.height(12.dp))
        HorizontalPager(
            state = pagerState,
            verticalAlignment = Alignment.Top
        ) { index ->
            WbItemList(data = pages[index])
        }
    }
}

@Composable
fun WbItemList(data: List<WbItem>) {
    val nestedScrollInteropConnection = rememberNestedScrollInteropConnection()
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .nestedScroll(nestedScrollInteropConnection),
    ) {
        items(
            items = data,
            key = { it.id },
        ) { item ->
            WbItem(item)
            Spacer(modifier = Modifier.height(4.dp))
        }
    }
}

@Composable
fun WbItem(
    item: WbItem,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White)
            .padding(horizontal = 16.dp, vertical = 12.dp)
    ) {
        Text(
            text = item.itemName,
            fontSize = 16.sp,
            fontWeight = FontWeight.ExtraBold,
            color = Color.Black
        )
        WbItemLine(item.content)
        WbItemLine(item.requirements)
        WbItemLine(item.note)
    }
}

@Composable
fun WbItemLine(value: String) {
    if (value.isNotEmpty()) {
        Text(text = value, fontSize = 15.sp)
    }
}